package com.ruoyi.znjc.service.impl;

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
@Service
public class ZnjcLLMService {

    private static final String API_KEY = "sk-tqyzqlvohqjaroeqjjwcottleiwbwfydtgmkcoxsytanzkvv"; // 你的API Key
    private static final String API_URL = "https://api.siliconflow.cn/v1/chat/completions";

    private final RestTemplate restTemplate;

    public ZnjcLLMService() {
        this.restTemplate = new RestTemplate();
    }

    // 你已有的方法
    public String chatWithLLM(String prompt) {
        Map<String, Object> body = new HashMap<>();
        body.put("model", "Qwen/Qwen3-30B-A3B-Instruct-2507");

        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", prompt);
        messages.add(message);

        body.put("messages", messages);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + API_KEY);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(API_URL, entity, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                return response.getBody();
            } else {
                return "调用大模型接口失败，状态码：" + response.getStatusCode();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "调用大模型接口异常：" + e.getMessage();
        }
    }

    // 新增：根据定时器数据自动生成提示并调用大模型
    public String chatWithTimerData(Map<String, Object> timerData) {
        String ruleContent = (String) timerData.get("ruleContent");
        List<String> environmentData = (List<String>) timerData.get("environmentData");

        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("你是农业病害诊断助手。\n");
        promptBuilder.append("根据以下规则内容（诊断依据）和环境数据（观测值），请判断是否发生病害并计算概率。\n\n");

        promptBuilder.append("规则内容（诊断依据）：\n");
        promptBuilder.append(ruleContent).append("\n\n");

        promptBuilder.append("环境数据列表（观测值）：\n");
        for (int i = 0; i < environmentData.size(); i++) {
            promptBuilder.append((i + 1) + ". " + environmentData.get(i)).append("\n");
        }

        promptBuilder.append("\n请严格按照以下JSON格式输出，且仅输出JSON，不要多余说明：\n");
        promptBuilder.append("{\n  \"disease\": \"病害名称\" 或 null,\n  \"probability\": 数字\n}\n");
        promptBuilder.append("如果病害概率低于50%，请输出 disease 为 null，probability 为 0。\n");

        return chatWithLLM(promptBuilder.toString());
    }

}
